package com.watson.tool.utils;


import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Properties;

public class SendmailUtil {

    public static String Email(String zhh) throws MessagingException {

        //设置随机验证码
        int sjs = (int) ((Math.random() * 9 + 1) * 100000);
        Properties properties = new Properties();
        // 连接协议
        properties.put("mail.transport.protocol", "smtp");
        // 主机名
        properties.put("mail.smtp.host", "smtp.qq.com");
        // 端口号
        properties.put("mail.smtp.port", 465);

        properties.put("mail.smtp.auth", "true");
        // 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.smtp.ssl.enable", "true");
        // 设置是否显示debug信息 true 会在控制台显示相关信息
        properties.put("mail.debug", "true");

        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址 *
        message.setFrom(new InternetAddress("2633034735@qq.com"));
        // 设置收件人地址*
        message.setRecipients(RecipientType.TO, new InternetAddress[]{new InternetAddress(zhh + "@qq.com")});
        // 设置邮件标题 *
        message.setSubject("这是第一封Java邮件");
        // 设置邮件内容 *
        message.setText(sjs + ""); // 为传过来的值

        // 得到邮差对象

        Transport transport = session.getTransport();

        // 连接自己的邮箱账户 *
        transport.connect("2633034735@qq.com", "uaigbxwopnseeafd");// 密码为刚才得到的授权码

        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        //返回验证码
        return sjs + "";

    }

    public static void main(String[] args) {

        try {
            String zhh = "2219563475";//发送给指定账号
            String code = SendmailUtil.Email(zhh);
            System.out.println("邮箱验证码：" + code);
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}
